Ext.ns('app');

Ext.tip.QuickTipManager.init();

Ext.data.DataReader.messageProperty = "msg";

Ext.define('app.comboModel', {
    extend: 'Ext.data.Model',
    fields: [
        {name:'id' ,  type:'integer'},
        {name:'title' , type:'string'}
    ]
});
Ext.define('app.comboStringModel', {
    extend: 'Ext.data.Model',
    fields: [
        {name:'id' ,  type:'string'},
        {name:'title' , type:'string'}
    ]
});

Ext.define('app.comboValueModel', {
    extend: 'Ext.data.Model',
    fields: [
        {name:'name' ,  type:'string'},
        {name:'value' , type:'string'}
    ]
});

Ext.data.proxy.Ajax.override({
   type: 'ajax',
   actionMethods : {
		create : 'POST',
		read   : 'POST',
		update : 'POST',
		destroy: 'POST'
   }
});

/**
 * Ext.window tools
 */
app.windowToolsElementsConfig = [
 {
	id:"restore",
	hidden:true,
	handler: function(event, toolEl, panel){
			panel.ownerCt.restore();    	
			panel.getComponent('maximize').show();
			panel.getComponent('restore').hide();
	}
 },{
	id:"maximize",
	handler: function(event, toolEl, panel){
		panel.ownerCt.maximize();
		panel.getComponent('maximize').hide();
		panel.getComponent('restore').show();
	}
 }/*,{
	 id:'close',
	 handler: function(event, toolEl, panel){
			panel.ownerCt.close();
	}
 }*/
];
app.windowToolsElements = function(){
	return Ext.clone(app.windowToolsElementsConfig);
};

app.checkHeight = function(size){
	var viewSize = Ext.getBody().getViewSize();
	
	if( size > viewSize.height){
		return (viewSize.height * 0.9);
	}else{
		return size;
	}
};

app.checkWidth = function(size){
	var viewSize = Ext.getBody().getViewSize();
	
	if( size > viewSize.width){
		return (viewSize.width * 0.9);
	}else{
		return size;
	}
};

app.comboTpl = Ext.create('Ext.XTemplate', '<tpl for="."><div class=\"app-combo-item\">', '{title}','</div></tpl>');

app.getCookie = function(name) { 
    var prefix = name + "="; 
    var cookieStartIndex = document.cookie.indexOf(prefix); 
    if (cookieStartIndex == -1) return null; 
    var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length); 
    if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length; 
    return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex)); 
};

app.checkboxRenderer = function(value, metaData, record, rowIndex, colIndex, store){
	if(value){
		 return '<img src="/i/system/yes.gif" data-qtip="'+appLang.YES+'">';
	 }else{
		 return '<img src="/i/system/no.png" data-qtip="'+appLang.NO+'">';
	 }
};

app.publishRenderer = function(value, metaData, record, rowIndex, colIndex, store){
	 if(value){
		 metaData.tdCls ='publishedRender';
		 return '<img src="/i/system/yes.gif" data-qtip="'+appLang.PUBLISHED+'" />';
	 }else{
		 metaData.tdCls ='notPublishedRender';
		 return '<img src="/i/system/no.png" data-qtip="'+appLang.NOT_PUBLISHED+'" />';
	 }
};

app.formFailure = function(form, action) {
    switch (action.failureType) {
	    case Ext.form.Action.CLIENT_INVALID:
	        Ext.Msg.alert(appLang.MESSAGE, appLang.FILL_FORM);
	        break;
	    case Ext.form.Action.CONNECT_FAILURE:
	        Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);
	        break;
	    case Ext.form.Action.SERVER_INVALID:
	       Ext.Msg.alert(appLang.MESSAGE, action.result.msg);break;
	    default :   
	    	 Ext.Msg.alert(appLang.MESSAGE, action.result.msg);
	}
};

app.ajaxFailure = function(response, opts){
	 Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);
};

app.versionRenderer = function(value, metaData, record, rowIndex, colIndex, store ,view){ 
	
    var cur = record.get('published_version') ;
    var last = record.get('last_version') ;

    if(cur>=last && cur!=0){
		 metaData.tdCls = 'renderLast';
	 }else{
		 metaData.tdCls = 'renderNotLast';
	 }
  	return  cur +' / '+ last;
};

app.creatorRenderer = function(value, metaData, record, rowIndex, colIndex, store){
	var s = record.get('user');
	 
	if(!Ext.isEmpty(record.get('date_created'))){
		 s+=  ' on ' + Ext.Date.format(record.get('date_created') , 'M d, Y H:i:s');
	} 
	metaData.attr='data-qtip="'+s+'"';
	return  s;
};

app.updaterRenderer = function(value, metaData, record, rowIndex, colIndex, store){ 
	 var s = record.get('updater');
	 
	if(!Ext.isEmpty(record.get('date_updated'))){
	    s+=' on '+  Ext.Date.format(record.get('date_updated'), 'M d, Y H:i:s' );
	} 
	metaData.attr='data-qtip="'+s+'"';
	return  s;
};

app.sotrColumn = {
    	xtype:'actioncolumn',
    	width:60,
    	tooltip:appLang.REMOVE_ITEM,
    	dataIndex:'id',
    	items:[
    	       {
    	    	   icon: '/i/system/down.png',
    	    	   handler:function(grid, rowIndex, colIndex){
    	    		   var total = grid.getStore().getCount();
    	    		   if(rowIndex == total - 1)
    	    			   return;
    	    		   
    	    		   var sRec = grid.getStore().getAt(rowIndex);
    	    		   grid.getStore().removeAt(rowIndex);
    	    		   grid.getStore().insert(rowIndex+1 , sRec);
    	    		   //grid.getStore().commitChanges();
    	    		   
    	    	  }
    	       },{
    	    	   icon: '/i/system/up.png',
    	    	   handler:function(grid, rowIndex, colIndex){
    	    		   var total = grid.getStore().getCount();
    	    		   if(rowIndex == 0)
    	    			   return;
    	    		   
    	    		   var sRec = grid.getStore().getAt(rowIndex);
    	    		   grid.getStore().removeAt(rowIndex);
    	    		   grid.getStore().insert(rowIndex -1 , sRec);
    	    		   //grid.getStore().commitChanges();
    	    	   }
    	       },{
    	    	   icon:'/i/system/delete.gif',
    	    	   handler:function(grid, rowIndex, colIndex){
    	    			   grid.getStore().removeAt(rowIndex);
    	    			  // grid.getStore().commitChanges();
    	    	    }
    	       }
    	]
    };

app.linesRenderer = function(value, metaData, record, rowIndex, colIndex, store){
	metaData.attr = 'style="display:block;white-space:normal;"';
	return value;
};


Ext.define('app.jsonStoreCollectable',{
	extend:'Ext.data.Store',
	fieldName:null,
	url:null,
	
	construct:function(){
		
		config = Ext.apply({
			 	proxy: {
			        type: 'ajax',
			    	url:config.url,
			        reader: {
			            type: 'json',
			            root: 'data',
			            idProperty: 'id'
			        }
			    },
			    remoteSort: false,
			    simpleSortMode: true,
			    autoLoad: true
	    }, config);		
		delete config.url;
		this.callParent(arguments);
	},
	collectData:function(){
		var list = [];
		this.each(function(record){
			if(!record.get('deleted')){
				list[list.length] = record.get('id');
			}
		});
		return list;
	},
	setData:function(data){
		this.removeAll();
		this.loadData(data);
	}
});
/**
 * check if value in array
 * @param value
 * @param array
 * @returns {Boolean}
 */
app.inArray = function(value , array){
    for(var i=0; i < array.length; i++)
        if(value == array[i]) 
            return true;
    return false;
};
/**
 * Allow/disalow edit column
 * @param grid
 * @param colId
 * @param state
 */
app.setColumnEditable = function(grid, colId, state){
	var count = grid.getColumnModel().getColumnCount();
    var col;
 
	 for(var i=0; i<count; i++){ 
		 if((Ext.isArray(colId) && app.inArray(grid.colModel.getColumnId(i), colId)) || (!Ext.isArray(colId) && grid.colModel.getColumnId(i) == colId))
			 grid.colModel.setEditable(i, state);
	 }
};

/**
 * @param {Ext.data.proxy.Proxy} model
 * @param {Object} response - The response from the AJAX request
 * @param {Ext.data.Operation} operation - The operation that triggered request
 * @param {Object} eOpts - The options object passed to Ext.util.Observable.addListener.
 */
app.storeException = function(model, response, operation, eOpts){
	resp =  Ext.JSON.decode(response.responseText);
	switch(operation.action){
		case 'response' :  Ext.Msg.alert(appLang.MESSAGE, appLang.INVALID_RESPONSE);
						   break;
		case 'remote':
						   Ext.Msg.alert(appLang.MESSAGE, resp.msg);
						   break;
		case 'create':
		
		
			Ext.Msg.alert(appLang.MESSAGE, resp.msg);
			break;
	}
};


app.createUrl = function(paths){
	return paths.join(app.delimeter);
};


// Add the additional 'advanced' VTypes
Ext.apply(Ext.form.field.VTypes, {
    password: function(val, field) {
        if (field.initialPassField) {
            var pwd = field.up('form').getForm().findField(field.initialPassField);
            return (val == pwd.getValue());
        }
        return true;
    },
    passwordText: appLang.PASSNOTMATCH
});


function number_format( number, decimals, dec_point, thousands_sep ) {	// Format a number with grouped thousands
	// 
	// +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +	 bugfix by: Michael White (http://crestidg.com)

	var i, j, kw, kd, km;

	// input sanitation & defaults
	if( isNaN(decimals = Math.abs(decimals)) ){
		decimals = 2;
	}
	if( dec_point == undefined ){
		dec_point = ",";
	}
	if( thousands_sep == undefined ){
		thousands_sep = ".";
	}

	i = parseInt(number = (+number || 0).toFixed(decimals)) + "";

	if( (j = i.length) > 3 ){
		j = j % 3;
	} else{
		j = 0;
	}

	km = (j ? i.substr(0, j) + thousands_sep : "");
	kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
	//kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
	kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");


	return km + kw + kd;
}

app.collectStoreData = function(store, idProperty){
	var newRec = store.getNewRecords();
	var updRec = store.getUpdatedRecords();
	var allPec = newRec.concat(updRec);
	var data = [];
	
	Ext.each(allPec, function(item,index){
		data.push(item.data);
	},this);
	
//	Ext.each(newRec, function(item,index){
//		var curent = item.data;
//		curent[idProperty] = item.get(idProperty);
//		data.push(curent);
//	},this);
//	
//	Ext.each(updRec, function(item,index){
//		var curent = item.getChanges();
//		curent[idProperty] = item.get(idProperty);
//		data.push(curent);
//	},this);
	return data;
};